<template>
  <div class="grade-review">
    <div class="header">
      <h2>成绩审核</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-row">
          <div class="form-group">
            <label>学年：</label>
            <el-select v-model="searchForm.academicYear" placeholder="请选择学年" clearable>
              <el-option label="2024-2025" value="2024-2025" />
              <el-option label="2023-2024" value="2023-2024" />
              <el-option label="2022-2023" value="2022-2023" />
            </el-select>
          </div>
          <div class="form-group">
            <label>学期：</label>
            <el-select v-model="searchForm.semester" placeholder="请选择学期" clearable>
              <el-option label="第一学期" value="第一学期" />
              <el-option label="第二学期" value="第二学期" />
            </el-select>
          </div>
          <div class="form-group">
            <label>课程名称：</label>
            <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" clearable />
          </div>
          <div class="form-group">
            <label>教师姓名：</label>
            <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名" clearable />
          </div>
          <div class="form-group">
            <label>审核状态：</label>
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" value="2" />
              <el-option label="已通过" value="3" />
              <el-option label="已退回" value="4" />
            </el-select>
          </div>
        </div>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button 
            type="success" 
            :disabled="selectedGrades.length === 0"
            @click="handleBatchApprove"
          >
            批量通过
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedGrades.length === 0"
            @click="handleBatchReject"
          >
            批量退回
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stat-card pending">
        <div class="stat-icon">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ pendingCount }}</div>
          <div class="stat-label">待审核</div>
        </div>
      </div>
      <div class="stat-card approved">
        <div class="stat-icon">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ approvedCount }}</div>
          <div class="stat-label">已通过</div>
        </div>
      </div>
      <div class="stat-card rejected">
        <div class="stat-icon">
          <el-icon><Close /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ rejectedCount }}</div>
          <div class="stat-label">已退回</div>
        </div>
      </div>
      <div class="stat-card total">
        <div class="stat-icon">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalCount }}</div>
          <div class="stat-label">总计</div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        stripe 
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="teacherName" label="任课教师" width="100" />
        <el-table-column prop="academicYear" label="学年" width="100" />
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column prop="usualScore" label="平时成绩" width="100">
          <template #default="scope">
            {{ scope.row.usualScore || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="examScore" label="考试成绩" width="100">
          <template #default="scope">
            {{ scope.row.examScore || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="总成绩" width="100">
          <template #default="scope">
            <span class="total-score">{{ scope.row.totalScore || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="letterGrade" label="等级" width="80">
          <template #default="scope">
            <el-tag :type="getGradeTagType(scope.row.letterGrade)">
              {{ scope.row.letterGrade || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="提交时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="success" 
              size="small" 
              @click="handleApprove(scope.row)"
              :disabled="scope.row.status !== 2"
            >
              通过
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleReject(scope.row)"
              :disabled="scope.row.status !== 2"
            >
              退回
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核对话框 -->
    <el-dialog 
      v-model="reviewDialogVisible" 
      :title="reviewDialogTitle"
      width="500px"
    >
      <div class="review-form">
        <div class="grade-info">
          <h4>成绩信息</h4>
          <div class="info-row">
            <span class="label">学生：</span>
            <span>{{ currentGrade?.studentName }} ({{ currentGrade?.studentNo }})</span>
          </div>
          <div class="info-row">
            <span class="label">课程：</span>
            <span>{{ currentGrade?.courseName }}</span>
          </div>
          <div class="info-row">
            <span class="label">教师：</span>
            <span>{{ currentGrade?.teacherName }}</span>
          </div>
          <div class="info-row">
            <span class="label">总成绩：</span>
            <span class="score">{{ currentGrade?.totalScore }} ({{ currentGrade?.letterGrade }})</span>
          </div>
        </div>
        
        <div class="review-section">
          <h4>审核意见</h4>
          <el-input
            v-model="reviewComment"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见（选填）"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button 
            v-if="reviewAction === 'approve'"
            type="success" 
            @click="confirmReview"
          >
            确认通过
          </el-button>
          <el-button 
            v-if="reviewAction === 'reject'"
            type="danger" 
            @click="confirmReview"
          >
            确认退回
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="成绩详情"
      width="600px"
    >
      <div class="grade-detail" v-if="currentGrade">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">学生姓名：</span>
              <span>{{ currentGrade.studentName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">学号：</span>
              <span>{{ currentGrade.studentNo }}</span>
            </div>
            <div class="detail-item">
              <span class="label">课程名称：</span>
              <span>{{ currentGrade.courseName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">任课教师：</span>
              <span>{{ currentGrade.teacherName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">学年学期：</span>
              <span>{{ currentGrade.academicYear }} {{ currentGrade.semester }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>成绩信息</h4>
          <div class="score-detail">
            <div class="score-item">
              <span class="label">平时成绩：</span>
              <span class="value">{{ currentGrade.usualScore || '--' }}</span>
            </div>
            <div class="score-item">
              <span class="label">考试成绩：</span>
              <span class="value">{{ currentGrade.examScore || '--' }}</span>
            </div>
            <div class="score-item total">
              <span class="label">总成绩：</span>
              <span class="value">{{ currentGrade.totalScore || '--' }}</span>
            </div>
            <div class="score-item grade">
              <span class="label">等级：</span>
              <el-tag :type="getGradeTagType(currentGrade.letterGrade)">
                {{ currentGrade.letterGrade || '--' }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="detail-section" v-if="currentGrade.reviewComment || currentGrade.reviewerName">
          <h4>审核信息</h4>
          <div class="review-info">
            <div class="info-item" v-if="currentGrade.reviewerName">
              <span class="label">审核人：</span>
              <span>{{ currentGrade.reviewerName }}</span>
            </div>
            <div class="info-item" v-if="currentGrade.reviewTime">
              <span class="label">审核时间：</span>
              <span>{{ formatDate(currentGrade.reviewTime) }}</span>
            </div>
            <div class="info-item" v-if="currentGrade.reviewComment">
              <span class="label">审核意见：</span>
              <div class="comment">{{ currentGrade.reviewComment }}</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, Check, Close, Document } from '@element-plus/icons-vue'
import { gradeAdminApi } from '@/api/grade'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedGrades = ref([])
const reviewDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentGrade = ref(null)
const reviewComment = ref('')
const reviewAction = ref('')

// 搜索表单
const searchForm = reactive({
  academicYear: '',
  semester: '',
  courseName: '',
  teacherName: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 统计数据
const pendingCount = computed(() => tableData.value.filter(item => item.status === 2).length)
const approvedCount = computed(() => tableData.value.filter(item => item.status === 3).length)
const rejectedCount = computed(() => tableData.value.filter(item => item.status === 4).length)
const totalCount = computed(() => tableData.value.length)

// 计算属性
const reviewDialogTitle = computed(() => {
  return reviewAction.value === 'approve' ? '审核通过' : '审核退回'
})

// 页面加载时获取数据
onMounted(() => {
  console.log('=== 当前用户信息 ===')
  console.log('用户Store:', userStore.currentUser)
  console.log('用户角色:', userStore.currentUser?.roles)
  console.log('用户登录状态:', userStore.isLoggedIn)
  
  // 先测试基本的API是否能访问
  testApiAccess()
})

// 测试API访问
const testApiAccess = async () => {
  try {
    console.log('=== 测试API访问 ===')
    
    const testParams = {
      pageNum: 1,
      pageSize: 10
    }
    
    console.log('测试API参数:', testParams)
    
    const response = await gradeAdminApi.getPendingGrades(testParams)
    
    console.log('API响应成功:', response)
    
    if (response && response.code === 200) {
      console.log('API访问成功，开始加载成绩列表')
      loadGrades()
    } else {
      console.error('API访问失败:', response)
      ElMessage.error(`API访问失败: ${response.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('测试API访问出错:', error)
    console.error('错误详情:', error.response)
    
    let errorMessage = 'API访问失败'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  }
}

// 加载成绩列表
const loadGrades = async () => {
  loading.value = true
  try {
    console.log('=== 开始获取成绩列表 ===')
    
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    
    console.log('API请求参数:', params)
    
    const response = await gradeAdminApi.getPendingGrades(params)
    
    console.log('API响应成功:', response)
    
    if (response && response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
      console.log('设置tableData成功:', tableData.value)
    } else {
      console.log('响应码不是200:', response)
      ElMessage.error('响应格式错误')
    }
  } catch (error) {
    console.error('API请求失败:', error)
    console.error('错误详情:', error.response)
    
    let errorMessage = '获取成绩列表失败'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadGrades()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 单个通过
const handleApprove = (row) => {
  currentGrade.value = row
  reviewAction.value = 'approve'
  reviewComment.value = ''
  reviewDialogVisible.value = true
}

// 单个退回
const handleReject = (row) => {
  currentGrade.value = row
  reviewAction.value = 'reject'
  reviewComment.value = ''
  reviewDialogVisible.value = true
}

// 确认审核
const confirmReview = async () => {
  try {
    const status = reviewAction.value === 'approve' ? 3 : 4
    
    console.log('=== 审核操作调试 ===')
    console.log('当前用户:', userStore.currentUser)
    console.log('用户ID:', userStore.currentUser?.id)
    console.log('用户名称:', userStore.currentUser?.name)
    
    const params = {
      gradeId: currentGrade.value.id,
      status,
      reviewComment: reviewComment.value || '',
      reviewerId: userStore.currentUser?.id,
      reviewerName: userStore.currentUser?.name || userStore.currentUser?.username || '未知用户'
    }
    
    console.log('审核请求参数:', params)
    
    // 验证必需参数
    if (!params.reviewerId) {
      ElMessage.error('无法获取审核人ID，请重新登录')
      return
    }
    
    if (!params.reviewerName) {
      ElMessage.error('无法获取审核人姓名，请重新登录')
      return
    }
    
    await gradeAdminApi.reviewGrade(params)
    ElMessage.success(reviewAction.value === 'approve' ? '审核通过成功' : '审核退回成功')
    reviewDialogVisible.value = false
    loadGrades()
  } catch (error) {
    console.error('=== 审核操作错误 ===')
    console.error('错误详情:', error)
    console.error('错误响应:', error.response)
    
    let errorMessage = '审核操作失败'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  }
}

// 批量通过
const handleBatchApprove = async () => {
  try {
    await ElMessageBox.confirm(`确认要批量通过选中的 ${selectedGrades.value.length} 条成绩吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 验证用户信息
    if (!userStore.currentUser?.id) {
      ElMessage.error('无法获取审核人ID，请重新登录')
      return
    }
    
    const reviewerName = userStore.currentUser?.name || userStore.currentUser?.username || '未知用户'
    if (!reviewerName || reviewerName === '未知用户') {
      ElMessage.error('无法获取审核人姓名，请重新登录')
      return
    }
    
    const gradeIds = selectedGrades.value.map(grade => grade.id)
    const params = {
      gradeIds,
      status: 3,
      reviewComment: '批量审核通过',
      reviewerId: userStore.currentUser.id,
      reviewerName: reviewerName
    }
    
    console.log('批量通过请求参数:', params)
    
    await gradeAdminApi.batchReviewGrade(params)
    ElMessage.success('批量审核通过成功')
    loadGrades()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

// 批量退回
const handleBatchReject = async () => {
  try {
    const { value: comment } = await ElMessageBox.prompt('请输入退回原因', '批量退回', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入退回原因',
      inputValidator: (value) => {
        if (!value || value.trim() === '') {
          return '退回原因不能为空'
        }
        return true
      }
    })
    
    // 验证用户信息
    if (!userStore.currentUser?.id) {
      ElMessage.error('无法获取审核人ID，请重新登录')
      return
    }
    
    const reviewerName = userStore.currentUser?.name || userStore.currentUser?.username || '未知用户'
    if (!reviewerName || reviewerName === '未知用户') {
      ElMessage.error('无法获取审核人姓名，请重新登录')
      return
    }
    
    const gradeIds = selectedGrades.value.map(grade => grade.id)
    const params = {
      gradeIds,
      status: 4,
      reviewComment: comment,
      reviewerId: userStore.currentUser.id,
      reviewerName: reviewerName
    }
    
    console.log('批量退回请求参数:', params)
    
    await gradeAdminApi.batchReviewGrade(params)
    ElMessage.success('批量退回成功')
    loadGrades()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量退回失败:', error)
      ElMessage.error('批量退回失败')
    }
  }
}

// 查看详情
const handleViewDetail = (row) => {
  currentGrade.value = row
  detailDialogVisible.value = true
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedGrades.value = selection.filter(item => item.status === 2)
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadGrades()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadGrades()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '--'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已保存',
    2: '待审核',
    3: '已通过',
    4: '已退回'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取成绩等级标签类型
const getGradeTagType = (grade) => {
  const typeMap = {
    'A': 'success',
    'B': 'primary',
    'C': 'warning',
    'D': 'info',
    'F': 'danger'
  }
  return typeMap[grade] || 'info'
}
</script>

<style scoped>
.grade-review {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form .form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-group label {
  white-space: nowrap;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 10px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-card.pending .stat-icon {
  background: #e6a23c;
}

.stat-card.approved .stat-icon {
  background: #67c23a;
}

.stat-card.rejected .stat-icon {
  background: #f56c6c;
}

.stat-card.total .stat-icon {
  background: #409eff;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.total-score {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.review-form {
  padding: 10px 0;
}

.grade-info, .review-section {
  margin-bottom: 20px;
}

.grade-info h4, .review-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.info-row .label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.score {
  color: #409eff;
  font-weight: bold;
}

.grade-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.score-detail {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.score-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
}

.score-item.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.score-item.grade {
  background: #f0f9ff;
}

.score-item .label {
  width: 80px;
  font-weight: 500;
}

.score-item .value {
  font-weight: bold;
  font-size: 16px;
}

.review-info .info-item {
  margin-bottom: 10px;
}

.review-info .label {
  display: inline-block;
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.comment {
  margin-top: 5px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
  color: #606266;
  line-height: 1.6;
}
</style> 